﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ConcordWinManager
{
    public partial class TemplateForm : Form
    {
        public Template template;

        private Form parentForm;

        public string typeTemplate = string.Empty;

        public TemplateForm(Form parentForm)
        {
            InitializeComponent();

            template = new Template();

            this.parentForm = parentForm;
        }

        public TemplateForm(Form parentForm, string type)
        {
            InitializeComponent();

            template = new Template();

            this.parentForm = parentForm;

            rbtnContractWithoutRassrochka.Enabled = false;
            rbtnContractWithRassrochka.Enabled = false;
            rbtnReclamation.Enabled = false;
            rbtnZamer.Enabled = false;
            rbtnCheck.Enabled = false;
            rbtnInstallation.Enabled = false;

            switch (type)
            {
                case "д":
                    rbtnContractWithoutRassrochka.Checked = true;
                    break;
                case "д+р":
                    rbtnContractWithRassrochka.Checked = true;
                    break;
                case "р":
                    rbtnReclamation.Checked = true;
                    break;
                case "з":
                    rbtnZamer.Checked = true;
                    break;
                case "к":
                    rbtnCheck.Checked = true;
                    break;
                case "м":
                    rbtnInstallation.Checked = true;
                    break;
                default:
                    this.Close();
                    break;
            }
        }

        BindingSource bs = new BindingSource();

        public void UpdateForm()
        {
            if (typeTemplate != "")
            {
                DataSet ds = new DataSet();

                Tools.RunWithProgressIndicator(this, delegate { template.SelectByType(this.typeTemplate, ref ds); });

                bs.DataSource = null;
                bs.Filter = "";
                bs.DataSource = ds.Tables[0];


                dataGridViewTable.DataSource = bs;//ds.Tables[0];
                dataGridViewTable.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                dataGridViewTable.Columns[0].Visible = false;
                dataGridViewTable.Columns[1].Visible = false;
                dataGridViewTable.Sort(dataGridViewTable.Columns[2], ListSortDirection.Ascending);

                dataGridViewTable.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dataGridViewTable.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

                dataGridViewTable.Refresh();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            TemplateEditForm templateEditForm = new TemplateEditForm(this, "Добавление");
            templateEditForm.ShowDialog();

            UpdateForm();
        }

        /// <summary>
        /// Просмотр шаблона в MS Word
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnView_Click(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private void tbxQuickSearch_TextChanged(object sender, EventArgs e)
        {
            Tools.QuickSearch(tbxQuickSearch.Text.Trim(), dataGridViewTable.Columns, ref this.bs);
        }

        private void rbtn_CheckedChanged(object sender, EventArgs e)
        {
            typeTemplate = (sender as RadioButton).Tag.ToString();
            if ((sender as RadioButton).Checked)
            {
                UpdateForm();
            }
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            int id;
            if (dataGridViewTable.SelectedRows.Count > 0)
            {
                if (int.TryParse(dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_template"].Value.ToString(), out id))
                {
                    TemplateEditForm templateEditForm = new TemplateEditForm(this, "Изменение", id);
                    templateEditForm.ShowDialog();
                }                
            }

            UpdateForm();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
             int id;
             if (dataGridViewTable.SelectedRows.Count > 0)
             {
                 if (int.TryParse(dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_template"].Value.ToString(), out id))
                 {
                     try
                     {
                     Tools.RunWithProgressIndicator(this, delegate {
                         template.SelectById(id);                         
                     });
                     
                         FileInfo fi = new FileInfo(template.SourceFilePath);
                         GZipHelper.Decompress(fi);

                         SaveFileDialog saveFileDialog = new SaveFileDialog();
                         saveFileDialog.Filter = "Все файлы |*.*";
                         saveFileDialog.FileName = template.Filename;

                         if (saveFileDialog.ShowDialog() == DialogResult.OK)
                         {
                             File.Copy(fi.DirectoryName + "\\" + template.Filename, saveFileDialog.FileName);
                         }
                     }
                     catch(Exception ex)
                     {
                         MessageBox.Show("При экспортировании шаблона произошла ошибка \n\n" + ex.Message, "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                     }                     
                 }
             }
        }

        private void btnChangeItem_Click(object sender, EventArgs e)
        {
            Tools.RunWithProgressIndicator(this, delegate
            {
                if (dataGridViewTable.SelectedRows.Count > 0)
                {
                    this.template.SelectById(
                        (int)dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_template"].Value);
                }
            });

            this.Close();
        }

        private void TemplateForm_Load(object sender, EventArgs e)
        {
            btnAdd.Visible = Settings.consultant.user.IsAdminRole;
            btnChange.Visible = Settings.consultant.user.IsAdminRole;
            btnExport.Visible = Settings.consultant.user.IsAdminRole;
        }

    }
}
